<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box1 {
        width: 100px;
        height: 100px;
        background: red;
        position: absolute;
      }

      .box2 {
        width: 100px;
        height: 100px;
        background: blue;
        left: 600px;
        position: absolute;
      }
    </style>
  </head>

  <body>
    <div class="box1"></div>
    <div class="box2"></div>
    <script>
      // 检测碰撞必须是2个元素 宽高一致；
      var box1Ele = document.querySelector(".box1");
      var box2Ele = document.querySelector(".box2");
      box1Ele.onmousedown = function (e) {
        var x = e.clientX - this.offsetLeft;
        var y = e.clientY - this.offsetTop;
        this.onmousemove = function (e) {
          var xx = e.clientX;
          var yy = e.clientY;
          this.style.left = xx - x + "px";
          this.style.top = yy - y + "px";

          // 检测和 蓝色方框的碰撞；
          // 红色方块的 离左边的距离
          var rx = this.offsetLeft;
          var ry = this.offsetTop;
          // 蓝色的方块 离左边的距离
          var bx = box2Ele.offsetLeft;
          var by = box2Ele.offsetTop;
          if (
            Math.abs(bx - rx) <= this.offsetWidth &&
            Math.abs(by - ry) <= this.offsetHeight
          ) {
            console.log("装了");
          }
        };
      };

      document.onmouseup = function () {
        box1Ele.onmousemove = "";
      };
    </script>
  </body>
</html>
